// 全局变量
let chatHistory = [];
let chronicChart = null;

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  initBooking();
  initResults();
  initPrescriptions();
  initHealthRecord();
  initChronic();
  initConsultation();
  initEducation();
  initPayment();
  initNavigation();
  initFeedback();
});

// 在线挂号
function initBooking() {
  const form = document.getElementById('form-booking');
  const output = document.getElementById('out-booking');
  
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = new FormData(form);
    const payload = Object.fromEntries(data);
    
    try {
      const res = await fetch('/api/booking', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const json = await res.json();
      
      if (json.ok) {
        output.textContent = `挂号成功！\n\n挂号编号: ${json.data.id}\n院区: ${json.data.hospital}\n科室: ${json.data.dept}\n医生: ${json.data.doctor}\n时段: ${json.data.slot}\n创建时间: ${json.data.createdAt}`;
        form.reset();
      } else {
        output.textContent = `挂号失败: ${json.error || '未知错误'}`;
      }
    } catch (err) {
      output.textContent = `网络错误: ${err.message}`;
    }
  });
}

// 检查检验查询
function initResults() {
  const btn = document.getElementById('btn-load-results');
  const list = document.getElementById('list-results');
  
  btn.addEventListener('click', async () => {
    try {
      const res = await fetch('/api/results');
      const json = await res.json();
      
      if (json.ok && json.data.length > 0) {
        list.innerHTML = json.data.map(item => `
          <div class="list-item">
            <h3>${item.type} - ${item.status}</h3>
            <p><strong>检查时间:</strong> ${item.time}</p>
            <p><strong>报告摘要:</strong> ${item.summary}</p>
            ${item.images && item.images.length > 0 ? `<div style="margin-top: 10px;"><img src="${item.images[0].url}" alt="${item.images[0].alt}" style="max-width: 100%; border-radius: 8px;" /></div>` : ''}
          </div>
        `).join('');
      } else {
        list.innerHTML = '<div class="muted">暂无检查报告</div>';
      }
    } catch (err) {
      list.innerHTML = `<div class="muted">加载失败: ${err.message}</div>`;
    }
  });
  
  // 自动加载一次
  btn.click();
}

// 电子处方
function initPrescriptions() {
  const btn = document.getElementById('btn-load-rx');
  const list = document.getElementById('list-rx');
  
  btn.addEventListener('click', async () => {
    try {
      const res = await fetch('/api/prescriptions');
      const json = await res.json();
      
      if (json.ok && json.data.length > 0) {
        list.innerHTML = json.data.map(item => `
          <div class="list-item">
            <h3>处方 ${item.id} - ${item.doctor}（${item.dept}）</h3>
            <p><strong>开具日期:</strong> ${item.date}</p>
            <p><strong>支持医保:</strong> ${item.insurance ? '是' : '否'}</p>
            <div style="margin-top: 10px;">
              <strong>药品清单:</strong>
              <ul style="margin-top: 5px; padding-left: 20px;">
                ${item.meds.map(m => `<li>${m.name} ${m.dose} ${m.freq}，共${m.days}天</li>`).join('')}
              </ul>
            </div>
          </div>
        `).join('');
      } else {
        list.innerHTML = '<div class="muted">暂无电子处方</div>';
      }
    } catch (err) {
      list.innerHTML = `<div class="muted">加载失败: ${err.message}</div>`;
    }
  });
  
  btn.click();
}

// 个人健康档案
function initHealthRecord() {
  const btn = document.getElementById('btn-load-record');
  const input = document.getElementById('inp-user');
  const output = document.getElementById('out-record');
  
  btn.addEventListener('click', async () => {
    const userId = input.value.trim() || 'u_demo';
    
    try {
      const res = await fetch(`/api/health-record/${userId}`);
      const json = await res.json();
      
      if (json.ok && Object.keys(json.data).length > 0) {
        const data = json.data;
        output.textContent = `个人健康档案 (用户: ${userId})
        
过敏史: ${data.allergies ? data.allergies.join('、') : '无'}

疾病史: ${data.medHistory ? data.medHistory.join('、') : '无'}

最近就诊:
${data.visitHistory ? data.visitHistory.map(v => `  - ${v.date} ${v.dept}: ${v.reason}`).join('\n') : '暂无'}

生活方式:
  运动: ${data.lifestyle?.exercise || '未记录'}
  饮食: ${data.lifestyle?.diet || '未记录'}`;
      } else {
        output.textContent = '暂无健康档案';
      }
    } catch (err) {
      output.textContent = `加载失败: ${err.message}`;
    }
  });
  
  btn.click();
}

// 慢病监测与管理
function initChronic() {
  const form = document.getElementById('form-metric');
  const btn = document.getElementById('btn-load-metrics');
  const input = document.getElementById('inp-user2');
  const canvas = document.getElementById('chart');
  
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = new FormData(form);
    const payload = {
      userId: 'u_demo',
      metric: {
        type: data.get('type'),
        systolic: data.get('systolic') || null,
        diastolic: data.get('diastolic') || null,
        value: data.get('value') || null,
        time: new Date().toISOString().slice(0, 16).replace('T', ' ')
      }
    };
    
    try {
      const res = await fetch('/api/chronic/record', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const json = await res.json();
      
      if (json.ok) {
        alert('记录成功！');
        form.reset();
        btn.click(); // 刷新图表
      }
    } catch (err) {
      alert(`记录失败: ${err.message}`);
    }
  });
  
  btn.addEventListener('click', async () => {
    const userId = input.value.trim() || 'u_demo';
    
    try {
      const res = await fetch(`/api/chronic/metrics/${userId}`);
      const json = await res.json();
      
      if (json.ok && json.data.length > 0) {
        drawChronicChart(json.data);
      } else {
        canvas.parentElement.innerHTML = '<div class="muted">暂无慢病监测数据</div>';
      }
    } catch (err) {
      alert(`加载失败: ${err.message}`);
    }
  });
  
  btn.click();
}

function drawChronicChart(data) {
  const ctx = document.getElementById('chart').getContext('2d');
  
  if (chronicChart) {
    chronicChart.destroy();
  }
  
  // 准备数据
  const labels = data.map(d => d.time.slice(5)).slice(-10); // 最近10条
  const bpData = data.filter(d => d.type === 'blood_pressure').map(d => d.systolic).slice(-10);
  const gluData = data.filter(d => d.type === 'blood_glucose').map(d => d.value).slice(-10);
  
  chronicChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: '收缩压 (mmHg)',
          data: bpData,
          borderColor: '#e74c3c',
          backgroundColor: 'rgba(231, 76, 60, 0.1)',
          tension: 0.4
        },
        {
          label: '血糖 (mmol/L)',
          data: gluData,
          borderColor: '#27ae60',
          backgroundColor: 'rgba(39, 174, 96, 0.1)',
          tension: 0.4
        }
      ]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true },
        title: { display: true, text: '慢病监测趋势' }
      },
      scales: {
        y: { beginAtZero: false }
      }
    }
  });
}

// 在线咨询（豆包AI）
function initConsultation() {
  const form = document.getElementById('form-chat');
  const input = document.getElementById('inp-chat');
  const chat = document.getElementById('chat');
  
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const message = input.value.trim();
    if (!message) return;
    
    // 添加用户消息
    addChatMessage('user', message);
    input.value = '';
    
    // 调用AI
    try {
      const res = await fetch('/api/consult', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message, history: chatHistory })
      });
      const json = await res.json();
      
      if (json.ok) {
        addChatMessage('assistant', json.reply);
        chatHistory.push({ role: 'user', content: message });
        chatHistory.push({ role: 'assistant', content: json.reply });
      } else {
        addChatMessage('assistant', `咨询失败: ${json.error || '未知错误'}`);
      }
    } catch (err) {
      addChatMessage('assistant', `网络错误: ${err.message}`);
    }
  });
  
  // 初始欢迎消息
  addChatMessage('assistant', '您好！我是豆包AI医疗助理，请描述您的症状、持续时间及伴随症状，我将为您提供初步建议。');
}

function addChatMessage(role, content) {
  const chat = document.getElementById('chat');
  const div = document.createElement('div');
  div.className = `chat-message ${role}`;
  div.textContent = content;
  chat.appendChild(div);
  chat.scrollTop = chat.scrollHeight;
}

// 健康科普
function initEducation() {
  const btn = document.getElementById('btn-load-edu');
  const list = document.getElementById('list-edu');
  
  btn.addEventListener('click', async () => {
    try {
      const res = await fetch('/api/education');
      const json = await res.json();
      
      if (json.ok && json.data.length > 0) {
        list.innerHTML = json.data.map(item => `
          <li class="list-item">
            <h3>${item.title}</h3>
            <p><a href="${item.link}" target="_blank" style="color: #667eea;">阅读全文 →</a></p>
          </li>
        `).join('');
      } else {
        list.innerHTML = '<li class="muted">暂无科普内容</li>';
      }
    } catch (err) {
      list.innerHTML = `<li class="muted">加载失败: ${err.message}</li>`;
    }
  });
  
  btn.click();
}

// 医疗支付
function initPayment() {
  const form = document.getElementById('form-pay');
  const output = document.getElementById('out-pay');
  
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = new FormData(form);
    const payload = Object.fromEntries(data);
    payload.amount = parseFloat(payload.amount);
    
    try {
      const res = await fetch('/api/pay', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const json = await res.json();
      
      if (json.ok) {
        output.textContent = `支付成功！\n\n交易编号: ${json.tradeNo}\n支付金额: ¥${json.amount}\n支付方式: ${json.method}\n状态: ${json.status}`;
        form.reset();
      } else {
        output.textContent = `支付失败: ${json.error || '未知错误'}`;
      }
    } catch (err) {
      output.textContent = `网络错误: ${err.message}`;
    }
  });
}

// 就医导航
function initNavigation() {
  const btn = document.getElementById('btn-load-map');
  const info = document.getElementById('nav-info');
  
  btn.addEventListener('click', async () => {
    try {
      const res = await fetch('/api/navigation');
      const json = await res.json();
      
      if (json.ok) {
        info.innerHTML = `
          <div style="margin-bottom: 15px;">
            <strong>${json.data.hospital}</strong><br>
            <span style="font-size: 14px;">${json.data.address}</span>
          </div>
          <div style="text-align: center;">
            <iframe 
              src="${json.data.mapIframe}" 
              width="100%" 
              height="300" 
              style="border: none; border-radius: 10px;"
              loading="lazy"
            ></iframe>
          </div>
        `;
      }
    } catch (err) {
      info.textContent = `加载失败: ${err.message}`;
    }
  });
  
  btn.click();
}

// 满意度反馈
function initFeedback() {
  const form = document.getElementById('form-feedback');
  
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = new FormData(form);
    const payload = Object.fromEntries(data);
    payload.score = parseInt(payload.score);
    
    try {
      const res = await fetch('/api/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const json = await res.json();
      
      if (json.ok) {
        alert('感谢您的反馈！');
        form.reset();
      }
    } catch (err) {
      alert(`提交失败: ${err.message}`);
    }
  });
}